'use client'

import { useEffect, useState } from 'react'

type Heading = {
  id: string
  text: string
  level: number
}

export default function TableOfContents() {
  const [headings, setHeadings] = useState<Heading[]>([])
  const [activeId, setActiveId] = useState('')

  useEffect(() => {
    // 获取所有标题元素，但排除已经由MarkdownContent组件处理过的元素
    const elements = Array.from(document.querySelectorAll('h2, h3'))
      .filter(el => !el.id.startsWith('content-heading-'));
    
    const headingElements = elements.map((element, index) => {
      if (!element.id) {
        element.id = `heading-${index}`
      }
      const anchor = document.createElement('a')
      anchor.href = `#${element.id}`
      anchor.className = 'anchor'
      anchor.innerHTML = '#'
      if (!element.querySelector('.anchor')) {
        element.insertBefore(anchor, element.firstChild)
      }
      return {
        id: element.id,
        text: element.textContent?.replace('#', '') || `标题 ${index + 1}`,
        level: Number(element.tagName.charAt(1))
      }
    })
    
    // 获取MarkdownContent组件中的标题元素
    const contentHeadings = Array.from(document.querySelectorAll('h2[id^="content-heading-"], h3[id^="content-heading-"]'))
      .map((element, index) => {
        // 获取标题文本，并移除锚点符号
        let text = element.textContent || `内容标题 ${index + 1}`;
        text = text.replace('#', '');
        
        return {
          id: element.id,
          text: text,
          level: Number(element.tagName.charAt(1))
        };
      });
    
    // 合并两组标题
    setHeadings([...headingElements, ...contentHeadings])

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id)
          }
        })
      },
      { 
        rootMargin: '-80px 0% -35% 0%',
        threshold: 0.5 
      }
    )

    // 观察所有标题元素，包括MarkdownContent组件中的标题
    elements.forEach((element) => observer.observe(element))
    
    // 同时观察MarkdownContent组件中的标题元素
    const contentHeadingElements = Array.from(document.querySelectorAll('h2[id^="content-heading-"], h3[id^="content-heading-"]'))
    contentHeadingElements.forEach((element) => observer.observe(element))
    
    return () => observer.disconnect()
  }, [])

  if (headings.length === 0) {
    return null
  }

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, id: string) => {
    e.preventDefault()
    const element = document.getElementById(id)
    if (element) {
      const offset = 80
      const elementPosition = element.getBoundingClientRect().top + window.scrollY
      window.scrollTo({
        top: elementPosition - offset,
        behavior: 'smooth'
      })
      setActiveId(id)
    }
  }

  return (
    <nav 
      className="lg:sticky lg:top-24 overflow-auto custom-scrollbar" 
      style={{ maxHeight: 'calc(100vh - 8rem)' }}
    >
      <h2 className="text-lg font-semibold mb-4 dark:text-white">目录</h2>
      <ul className="space-y-2">
        {headings.map((heading) => (
          <li
            key={heading.id}
            style={{ paddingLeft: `${(heading.level - 2) * 1}rem` }}
          >
            <a
              href={`#${heading.id}`}
              onClick={(e) => handleClick(e, heading.id)}
              className={`block py-1 text-sm hover:text-blue-600 transition-colors
                ${activeId === heading.id
                  ? 'text-blue-600 dark:text-blue-400'
                  : 'text-gray-600 dark:text-gray-400'
                }`}
            >
              {heading.text}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  )
}